/*
 * =====================================================================================
 *
 *       Filename:  util_sem.c
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2020年04月28日 17时20分59秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  YOUR NAME (), 
 *   Organization:  
 *
 * =====================================================================================
 */


#include "util_sem.h"
#include "util_debug.h"

sem_t *sem_bin_open(const char *path)
{
    unsigned int value = 1;
    sem_t *sem = sem_open(path, O_RDWR | O_CREAT, 0666, value);
    if(SEM_FAILED == sem) {
        debug_err("%s(): sem_open(%s), %s\n", __func__, path, strerror(errno));
        return NULL;
    }
    return sem;
}

int sem_bin_close(sem_t *sem)
{
    int ret = sem_close(sem);
    if(ret < 0) {
        debug_err("%s(): sem_close(), %s\n", __func__, strerror(errno));
        return -1;
    }

    return 0;
}

int sem_bin_unlink(const char *path)
{
    int ret = sem_unlink(path);
    if(ret < 0) {
        debug_err("%s(): sem_unlink(%s), %s\n", __func__, path, strerror(errno));
        return -1;
    }
    return 0;
}


int sem_bin_lock(sem_t *sem)
{
    int value;
    sem_getvalue(sem, &value);
    debug_print("[%d] %s(): before sem_wait, semvalue=%d\n",
            getpid(), __func__, value);
    int ret = sem_wait(sem);
    sem_getvalue(sem, &value);
    debug_print("[%d] %s(): after sem_wait, semvalue=%d\n",
            getpid(), __func__, value);
    if(0 != ret) {
        debug_err("%s(): sem_wait(), %s\n", __func__, strerror(errno));
        sem_bin_close(sem);
        return -1;
    }
    return 0;
}

int sem_bin_unlock(sem_t *sem)
{
    int value;
    sem_getvalue(sem, &value);
    debug_print("[%d] %s(): before sem_post, semvalue=%d\n",
            getpid(), __func__, value);
    int ret = sem_post(sem);
    sem_getvalue(sem, &value);
    debug_print("[%d] %s(): after sem_post, semvalue=%d\n",
            getpid(), __func__, value);
    if(0 != ret) {
        debug_err("%s(): sem_post(), %s\n", __func__, strerror(errno));
        sem_bin_close(sem);
        return -1;
    }

    return 0;
}

